package com.zcoj.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zcoj.core.model.ApiResponse;
import com.zcoj.core.model.ApiResponseEnum;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
 
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value()); // 设置 HTTP 状态码为 200
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置响应内容类型为 JSON
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); // 设置响应编码为 UTF-8
        ApiResponse apiResponse = ApiResponse.failed(ApiResponseEnum.USER_NOT_LOGGED.getCode(),ApiResponseEnum.USER_NOT_LOGGED.getMessage()); // 构造响应数据
        String json = new ObjectMapper().writeValueAsString(apiResponse); // 将响应数据转换成 JSON 字符串
        response.getWriter().write(json); // 将响应数据写入响应体中
    }
}
